package org.gesplan.ui;

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.beans.Beans;
import java.util.List;
import java.util.ResourceBundle;
import java.util.logging.Logger;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import org.gesplan.util.RefreshWorker;
import org.gesplan.util.SortWorker;
import org.gesplan.util.Utils;

/**
 *
 * @author David
 */
public abstract class AbstractPanel extends JPanel {

    protected final ResourceBundle bundle;
    protected static Logger logger;
    protected EntityManager entityManager;
    protected SortWorker sortWorker;
    protected RefreshWorker refreshWorker;
    protected int sortOrder;


    public AbstractPanel() {
        bundle = Utils.getBundle();
        logger = Utils.getLogger();
        try {
            if (!Beans.isDesignTime()) {
                entityManager = Utils.getEntityManagerFactory().createEntityManager();
                refreshWorker = new RefreshWorker(this, entityManager, abstractQuery, abstractList);
            }
            initComponents();
        } catch (Exception e) {
            JOptionPane.showMessageDialog(abstractTable, bundle.getString("ERROR_DB_CONNECTION"), "Error", JOptionPane.ERROR_MESSAGE);
            logger.severe(e.getMessage());
            System.exit(-1);
        }
        initConfig();
    }


    private void initConfig() {
//        Dimension pantalla = Toolkit.getDefaultToolkit().getScreenSize();
//        Dimension finestra = getSize();
//        this.setLocation((pantalla.width - finestra.width) / 2, (pantalla.height - finestra.height) / 2);
        setVisible(true);
    }


    protected void initSorter() {
        sortWorker = new SortWorker(this, abstractTable);
        abstractTable.getTableHeader().addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                super.mouseClicked(e);
                int header = abstractTable.getTableHeader().columnAtPoint(e.getPoint());
                boolean order = (sortOrder % 2 == 0);
                sortWorker.setColumn(header, order);
                sortWorker.execute();
                ++sortOrder;
            }
        });
    }


    protected void newRecord() {
        int row = abstractList.size() - 1;
        abstractTable.setRowSelectionInterval(row, row);
        abstractTable.scrollRectToVisible(abstractTable.getCellRect(row, 0, true));
    }


    protected void save() {
    }


    protected void delete() {
    }


    protected boolean deleteConfirm() {
        if (abstractTable.getSelectedRows().length > 0) {
            int res = Utils.askQuestionYesNo(this, bundle.getString("DELETE_QUESTION"), bundle.getString("DELETE_CONFIRM"));
            return (res == 0);
        }
        return false;
    }


    protected void refresh(Query queryParam) {
        refreshWorker = new RefreshWorker(this, entityManager, queryParam);
        refreshWorker.setList(abstractList);
        refreshWorker.execute();
    }


    protected void refresh(Query queryParam, List<?> listObject) {
        refreshWorker = new RefreshWorker(this, entityManager, queryParam, listObject);
        refreshWorker.execute();
    }


    protected void previous() {
        if (entityManager.getTransaction().isActive()) {
            entityManager.getTransaction().rollback();
        }
        if (abstractTable.getSelectedRow() > 0) {
            abstractTable.getSelectionModel().setSelectionInterval(abstractTable.getSelectionModel().getMinSelectionIndex() - 1, abstractTable.getSelectionModel().getMinSelectionIndex() - 1);
            abstractTable.scrollRectToVisible(abstractTable.getCellRect(abstractTable.getSelectedRow(), 0, true));
        }
    }


    protected void next() {
        if (entityManager.getTransaction().isActive()) {
            entityManager.getTransaction().rollback();
        }
        if (abstractTable.getSelectedRow() + 1 < abstractTable.getRowCount()) {
            abstractTable.getSelectionModel().setSelectionInterval(abstractTable.getSelectionModel().getMinSelectionIndex() + 1, abstractTable.getSelectionModel().getMinSelectionIndex() + 1);
            abstractTable.scrollRectToVisible(abstractTable.getCellRect(abstractTable.getSelectedRow(), 0, true));
        }
    }


    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings({ "unchecked", "rawtypes" })
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        abstractQuery = null; // NOI18N;
        abstractList = java.util.Collections.emptyList();
        masterScrollPane = new javax.swing.JScrollPane();
        abstractTable = new javax.swing.JTable();

        org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, abstractList, abstractTable);
        bindingGroup.addBinding(jTableBinding);
        jTableBinding.bind();
        masterScrollPane.setViewportView(abstractTable);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(masterScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 683, Short.MAX_VALUE)
                .addGap(10, 10, 10))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(19, 19, 19)
                .addComponent(masterScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 137, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(53, Short.MAX_VALUE))
        );

        bindingGroup.bind();
    }// </editor-fold>//GEN-END:initComponents
    // Variables declaration - do not modify//GEN-BEGIN:variables
    @SuppressWarnings("rawtypes")
	protected java.util.List abstractList;
    protected javax.persistence.Query abstractQuery;
    protected javax.swing.JTable abstractTable;
    protected javax.swing.JScrollPane masterScrollPane;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables
}